<?php
/**
 * Created by PhpStorm.
 * User: 陶然
 * Date: 2019/4/10
 * Time: 14:25
 * SOURCE: 中国大陆工时规管现况（标准工时）：
 *              一天工作时间为8小时，平均每周工时不超过40小时;
 *              加班上限为一天3小时及一个月36小时，逾时工作薪金不低于平日工资的150％。
 *              而一周最高工时则为48小时。平均每月计薪天数为21.75天。
 * TO: 我是陶然,健康撸代码,拒绝通宵。
 * CLASS: < 聚聚模块 >
 */
namespace App\HttpController\Taoran;

use App\Common\Checking;
use App\HttpController\V1\BaseWithDb;
use App\Tools\Token\Token;
use EasySwoole\EasySwoole\Config;

class Agglomeration extends BaseWithDb
{
    /**
     * @return bool
     * 地区列表
     */
    function address_list()
    {
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $address=$this->db->where('class_id',$classId,'in')->getColumn('study','city');
        $data=[];
        foreach ($address as $v){
            $val=explode('/',$v);
            if (count($val)>=2) {
                if(!empty($data[$val[0]]) && !in_array($val[1],$data[$val[0]])){
                    $data[$val[0]][] = $val[1];
                }
            }elseif(count($val)==1){
                $data[$val[0]][] = [];
            }
        }
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 聚聚列表
     */
    function lists()
    {
        $parmer=$this->input('','post');
        if (!Checking::keyIsExistence('page',$parmer)){
            return $this->writeJson(201,'','参数不能为空');
        }
        if ($parmer['page']!=intval($parmer['page']) || $parmer['page']<1){
            return $this->writeJson(202,'','请求页码异常');
        }
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $this->db->where('class_id',$classId,'in');
        if (!empty($parmer['time'])){
            switch ($parmer['time']){
                case 1:  //今天
                    $this->db->where('`date`',date('Y-m-d').'%','like');
                    break;
                case 2:   //明天
                    $this->db->where('`date`',date('Y-m-d',time()+60*60*24).'%','like');
                    break;
                case 3:    //本周
                    $this->db->where('`date`',date('Y-m-d',(time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)),'>');
                    $this->db->where('`date`',date('Y-m-d',(time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600)),'<');
                    break;
                case 4:   //本周末
                    $this->db->where('`date`',date('Y-m-d',strtotime('Saturday')),'>');
                    $this->db->where('`date`',date('Y-m-d',strtotime('Sunday')),'<');
                    break;
                case 5:    //本月
                    $this->db->where('`date`',date('Y-m').'%','like');
                    break;
            }
        }
        if (!empty($parmer['address'])) {
            $this->db->where('city', $parmer['address'].'%','like');
        }
        $data=$this->db->orderBy('`date`','desc')->get('study',[($parmer['page']-1)*10,10],'id,study_title,image,city,date,time,market_price,state');
        foreach ($data as $k=>$v){
            if (!strstr($v['image'],'http://')){
                $data[$k]['image']=QINIU_URL.$v['image'];
            }
            $data[$k]['city']=str_replace('/',' ',$v['city']);
            $data[$k]['date']=date('m/d',strtotime($v['date']));
            $turn_time=date('h:i',strtotime($v['date']));
            $on_time=date('h:i',strtotime($v['date'])+$v['time']*60*60);
            if ($on_time<$turn_time){
                $on_time=$on_time.'(次日)';
            }
            $data[$k]['time']=$turn_time.'-'.$on_time;
            if ($v['market_price']==0){
                $data[$k]['market_price']='免费';
            }
            if ($v['state']==0){
                $data[$k]['market_price']='已结束';
            }
        }
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 聚聚详情
     */
    function details()
    {
        $ids=$this->input('ids','post');
        if (intval($ids)!=$ids){
            return $this->writeJson(201,'','传值错误');
        }
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $data=$this->db->where('id',$ids)->where('class_id',$classId,'in')->getOne('study');
        if (!$data){
            return $this->writeJson(202,'','不存在该活动');
        }
        $turn_time=date('h:i',strtotime($data['date']));
        $on_time=date('h:i',strtotime($data['date'])+$data['time']*60*60);
        if ($on_time<$turn_time){
            $on_time=$on_time.'(次日)';
        }
        $status=1;
        $collection_status=1;
        $userData=$this->getUsers();
        $adminHome=[];
        $this->db->where('id',$ids)->setInc('study','browse',1);
        if ($userData!=false) {
            if ($this->db->where('study_id',$ids)->where('user_id',$userData->id)->getOne('users_collection')){
                $collection_status=2;
            }
            if ($this->db->where('user_id',$userData->id)->where('activity_id',$ids)->getOne('activitys')){
                $status=2;
            }
        }else{
            $userId=$this->input('user_id','get');
            if (!empty($userId)){
                $adminHome=$this->db->where('id',$userId)->getOne('users','mobile,nickname,sign');
                if (!$adminHome['sign']){
                    $adminHome['sign']='书中有远方,我的声音里有声音的曙光';
                }
            }
        }
        if ($data['state']==0){
            $status=3;
        }
        $list=[
            'id'=>$data['id'],
            'user_id'=>is_array($userData)?$userData->id:0,
            'image'=>!strstr($data['image'],'http://')?QINIU_URL.$data['image']:$data['image'],
            'name'=>$data['study_title'],
            'browse'=>$data['browse'],
            'favorite'=>$data['favorite'],
            'date'=>date('m/d',strtotime($data['date'])),
            'time'=>$turn_time.'-'.$on_time,
            'address'=>str_replace('/',' ',$data['city']).'  '.$data['address'],
            'vip_price'=>$data['vip_price'],
            'market_price'=>$data['market_price'],
            'content'=>$data['introduce'],
            'status'=>$status,  //1正常 2报名  3结束
            'collection_status'=>$collection_status,  //1未收藏 2收藏
            'share_text'=>$data['share_text']
        ];
        $data=['list'=>$list,'user'=>$adminHome];
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 总结列表
     */
    function summary()
    {
        $parmer=$this->input('','post');
        if (!Checking::keyIsExistence('page',$parmer)){
            return $this->writeJson(201,'','参数不能为空');
        }
        if ($parmer['page']!=intval($parmer['page']) || $parmer['page']<1){
            return $this->writeJson(202,'','请求页码异常');
        }
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $this->db->where('class_id',$classId,'in');
        if (!empty($parmer['time'])){
            switch ($parmer['time']){
                case 1:  //今天
                    $this->db->where('`date`',date('Y-m-d').'%','like');
                    break;
                case 2:   //明天
                    $this->db->where('`date`',date('Y-m-d',time()+60*60*24).'%','like');
                    break;
                case 3:    //本周
                    $this->db->where('`date`',date('Y-m-d',(time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)),'>');
                    $this->db->where('`date`',date('Y-m-d',(time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600)),'<');
                    break;
                case 4:   //本周末
                    $this->db->where('`date`',date('Y-m-d',strtotime('Saturday')),'>');
                    $this->db->where('`date`',date('Y-m-d',strtotime('Sunday')),'<');
                    break;
                case 5:    //本月
                    $this->db->where('`date`',date('Y-m').'%','like');
                    break;
            }
        }
        if (!empty($parmer['address'])) {
            $this->db->where('city', $parmer['address'].'%','like');
        }
        $this->db->where('summary',null,'is not');
        $data=$this->db->orderBy('`date`','desc')->get('study',[($parmer['page']-1)*10,10],'id,study_title,image,city,date,time');
        foreach ($data as $k=>$v){
            if (!strstr($v['image'],'http://')){
                $data[$k]['image']=QINIU_URL.$v['image'];
            }
            $data[$k]['city']=str_replace('/',' ',$v['city']);
            $data[$k]['date']=date('m/d',strtotime($v['date']));
            $turn_time=date('h:i',strtotime($v['date']));
            $on_time=date('h:i',strtotime($v['date'])+$v['time']*60*60);
            if ($on_time<$turn_time){
                $on_time=$on_time.'(次日)';
            }
            $data[$k]['time']=$turn_time.'-'.$on_time;
            $data[$k]['study_title']=$v['study_title'].'总结';
        }
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 总结详情
     */
    function summary_details()
    {
        $ids=$this->input('ids','post');
        if (intval($ids)!=$ids){
            return $this->writeJson(201,'','传值错误');
        }
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $data=$this->db->where('id',$ids)->where('summary',null,'is not')->where('class_id',$classId,'in')->getOne('study');
        if (!$data){
            return $this->writeJson(202,'','该活动尚未总结');
        }
        $turn_time=date('h:i',strtotime($data['date']));
        $on_time=date('h:i',strtotime($data['date'])+$data['time']*60*60);
        if ($on_time<$turn_time){
            $on_time=$on_time.'(次日)';
        }
        $userData=$this->getUsers();
        $adminHome=[];
        $this->db->where('id',$ids)->setInc('study','browse',1);

        if (!is_array($userData)) {
            $userId=$this->input('user_id','get');
            if (!empty($userId)){
                $adminHome=$this->db->where('id',$userId)->getOne('users','mobile,nickname,sign');
                if (!$adminHome['sign']){
                    $adminHome['sign']='书中有远方,我的声音里有声音的曙光';
                }
            }
        }
        $data['summary']=str_replace('src="','src="'.ADMIN_URL,$data['summary']);
        $list=[
            'id'=>$data['id'],
            'user_id'=>is_array($userData)?$userData->id:0,
            'image'=>!strstr($data['image'],'http://')?QINIU_URL.$data['image']:$data['image'],
            'name'=>$data['study_title'].'总结',
            'browse'=>$data['browse'],
            'date'=>date('m/d',strtotime($data['date'])),
            'time'=>$turn_time.'-'.$on_time,
            'address'=>str_replace('/',' ',$data['city']).'  '.$data['address'],
            'content'=>$data['summary'],
        ];
        $data=['list'=>$list,'user'=>$adminHome];
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 返回用户登录信息
     */
    public function getUsers()
    {
//        $data = [
//            'id' => 1,
//            'pid' => 0,
//            'phone' =>15111111111,
//            'nickname' => 'system',
//            'headimgdetails' => '',
//            'token' => md5( time() . mt_rand( 1000, 9999 ) )
//        ];
//        $exprie = 24 * 60 * 60 * 1;
//        $jwt = Token::encode( $data, $exprie );
//        $jwt = $this->request()->getCookieParams( Config::getInstance()->getConf( 'TOKEN_NAME' ) );
        $jwt = $this->request()->getHeader( Config::getInstance()->getConf( 'TOKEN_NAME' ) )[0]??'';
        if (!$jwt){
            return false;
        }
        $data = Token::decode( $jwt );
        if ( $data['status'] != false) {
            return $data['content'];
        }
        return false;
    }
}